// pages/user/user.js
const app = getApp()
//初始化数据库
const db = wx.cloud.database()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userPhoto: "user/默认头像.png",
    nickName: "邓中从",
    logged:false, /*登录状态 */
    disabled: true,
    id: ''

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getLocation();
    
    wx.cloud.callFunction({
      name: 'login', // 这里的 'login' 就是云函数名
      data: { },
      success: result => {
          /*console.log('登录成功', result.result);*/
          db.collection('users').where({
            _openid: result.result.openid
          }).get().then((res)=>{
            if(res.data.length){
              app.userInfo = Object.assign(app.userInfo , res.data[0])
              //console.log("打印"+JSON.stringify(app.userInfo))
              this.setData({
                userPhoto: app.userInfo.userPhoto,
                nickName: app.userInfo.nickName,
                logged:true,
                id :app.userInfo._id
              });
              this.getMessage(); //登录的时候就获取消息
            }else{
              this.setData({
                disabled: false
              });
            }
          });
      },
      fail: err => {
          console.error('调用云函数失败', err);
      }
  });
  

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userPhoto: app.userInfo.userPhoto,
      nickName: app.userInfo.nickName,
      id :app.userInfo._id
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /**微信授权登录 后期要改*/
  bindGetUserInfo(ev){
    console.log(ev)
    let userInfo = ev.detail.userInfo;
    if(!this.data.logged && userInfo){
      db.collection('users').add({
        data:{
          userPhoto : userInfo.avatarUrl,
          nickName: userInfo.nickName,
          signature: '',
          phoneNumber:'',
          weixinNumber:'',
          gender: userInfo.gender,
          links: 0,
          time: new Date(),
          isLocation: true,  // 开启位置共享
          friendList: [],
          /*longitude:this.longitude,
          latitude: this.latitude,
          location:db.Geo.Point(this.longitude,this.latitude),*/
          des:'',
          standard:'',
          phonotos:'',
        }
      }).then((res)=>{
        /*console.log("rs"+JSON.stringify(res))*/
        /**存入全局中 */
        db.collection("users").doc(res._id).get().then((res)=>{
          /*console.log("添加结果"+JSON.stringify(res.data));*/
          app.userInfo = Object.assign(app.userInfo , res.data)
          this.setData({
            userPhoto: app.userInfo.userPhoto,
            nickName: app.userInfo.nickName,
            logged: true,
            id :app.userInfo._id
          });
        });
      });
    }
  },
  getFavorites(){
    db.collection('favorites').where({
      userId: app.userInfo._id
    }).watch({
      onChange: function(snapshot) {
        if(snapshot.docChanges.length){
          let list = snapshot.docChanges[0].doc.list;
          if(list.length){
            wx.showTabBarRedDot({
              index: 2
            });
            app.userFavorites = list;
          }else{
            wx.hideTabBarRedDot({
              index: 2,
            });
            app.userFavorites = [];
          }
        }
        console.log('docs\'s changed events', snapshot)
      },
      onError: function(err) {
        console.error('the watch closed because of error', err)
      }
    });
  },
  getMessage(){
    db.collection('message').where({
      userId: app.userInfo._id
    }).watch({
      onChange: function(snapshot) {
        if(snapshot.docChanges.length){
          let list = snapshot.docChanges[0].doc.list;
          if(list.length){
            wx.showTabBarRedDot({
              index: 2
            });
            app.userMessage = list;
          }else{
            wx.hideTabBarRedDot({
              index: 2,
            });
            app.userMessage = [];
          }
        }
        console.log('docs\'s changed events', snapshot)
      },
      onError: function(err) {
        console.error('the watch closed because of error', err)
      }
    });
  },
  getLocation(){
   /* wx.getLocation({
      type: 'gcj02',
      success:(res)=> {
        this.latitude = res.latitude
        this.longitude = res.longitude
        
      }
     })*/
  }
})